package com.demo.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

public class HelloScheduler2 {
    public static void main(String[] args) throws SchedulerException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(date));
        // 创建一个JobDetail实例，将该实例与HelloJob Class绑定
        JobDetail jobDetail = JobBuilder.newJob(HelloJob2.class)
                .withIdentity("myJob", "group1")
                .build();
        date.setTime(date.getTime() + 4000);
//        // 距离当前时间4秒钟后执行且只执行一次
//        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
//                .withIdentity("myTrigger", "group1")
//                .startAt(date)
//                .build();
        // 距离当前时间4秒钟后执行且只执行一次, 之后每隔两秒种重复执行一次任务
//        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
//                .withIdentity("myTrigger", "group1")
//                .startAt(date)
//                .withSchedule(SimpleScheduleBuilder.
//                        simpleSchedule().withIntervalInSeconds(2).withRepeatCount(3))
//                .build();
        // 距离当前时间4秒钟后执行且只执行一次, 之后每隔两秒种重复执行一次任务
        // 执行6秒后结束
        Date endDate = new Date();
        endDate.setTime(endDate.getTime() + 6000);
        SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                .withIdentity("myTrigger", "group1")
                .startAt(date)
                .endAt(endDate)
                .withSchedule(SimpleScheduleBuilder.
                        simpleSchedule().withIntervalInSeconds(2)
                        .withRepeatCount(3))
                .build();
        SchedulerFactory sfact = new StdSchedulerFactory();
        Scheduler scheduler = sfact.getScheduler();
        scheduler.start();
        scheduler.scheduleJob(jobDetail, trigger);
    }
}
